from flask import Flask, request, render_template, escape, jsonify
from geo import weather
import pandas as pd
import json


ldq_key = '37d910e782c83fc25f060611af2cab2a'

app = Flask(__name__)

def log_request(req:'flask_request', res:str) -> None:
    with open('city_weather.log', 'a') as log:
        print(req.form, req.remote_addr, req.user_agent, res, file=log, sep='|')

@app.route('/')
@app.route('/entry', methods=['GET', 'POST'])
def entry_page() -> 'html':
    return render_template('entry.html',
                           The_Title='欢迎来到天气查询屋^^',)


@app.route('/gaode_weather', methods=['GET', 'POST'])
def do_weather() ->'html':
        city = request.form['city']
        title = '这是今天的天气哦!'
        results = weather(city)
        data_list = pd.json_normalize(results)['lives']
        log_request(request, results)
        return render_template("results.html",
                               The_Title=title,
                               the_city=city,
                               the_resulte=data_list, )

@app.route('/viewlog', methods=['GET','POST'])
def view_the_log() -> 'html':
    contents = []
    with open('city_weather.log') as log:
        for line in log:
            contents.append([])
            for item in line.split('|'):
                contents[-1].append(escape(item))
    titles = ('hhhei')
    return render_template('viewlog.html',
                           the_title='VIEW LOG',
                           the_row_tltles=titles,
                           the_data=contents,)

if __name__=='__main__':
    app.run(debug=True)
